import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateMenuDto } from './dto/create-menu.dto'
import { UpdateMenuDto } from './dto/update-menu.dto'
import { Menu } from './entities/menu.entity'

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu) private readonly menu: Repository<Menu>
  ) {}
  async create(createMenuDto: CreateMenuDto) {
    const menu = new Menu()
    !createMenuDto.parentId
      ? (menu.parent = null)
      : (menu.parent = await this.menu.findOne({
          where: { id: createMenuDto.parentId }
        }))
    menu.name = createMenuDto.name
    menu.path = createMenuDto.path
    menu.desc = createMenuDto.desc
    menu.isFather = createMenuDto.isFather
    return this.menu.save(menu)
  }

  async findAll() {
    return await this.menu.find()
  }
  async findOne(id: number) {
    return await this.menu.findOne({ where: { id } })
  }

  update(id: number, updateMenuDto: UpdateMenuDto) {
    return this.menu.update(id, updateMenuDto)
  }

  remove(id: number) {
    return this.menu.softDelete(id)
  }

  restore(id: number) {
    return this.menu.restore(id)
  }
}
